package com.zige.zige.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zige.zige.R;
import com.zige.zige.constants.UrlConsts;
import com.zige.zige.pojo.UserInfo;
import com.zige.zige.task.PostRequestTask;
import com.zige.zige.task.TaskExecutor;
import com.zige.zige.utils.NetworkUtils;
import com.zige.zige.utils.SharedPreferencesUtils;
import com.zige.zige.utils.SystemUtils;
import com.zige.zige.utils.ToastUtils;

import org.json.JSONObject;

import java.util.HashMap;

/**
 * Created by Fei on 2015/11/5.
 */
public class ModifyPasswordActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout lay_back;
    private TextView tv_titlet,tv_forgetPassword;
    private Activity activity;
    private EditText oldPassword, newPassword, aginNewPassword;
    private UserInfo userInfo;
    private Button btn_commit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modifypassword);
        userInfo = application.getUserInfo();
        activity = this;
        initView();

    }

    private void initView() {
        lay_back = serchViewById(R.id.lay_back);
        lay_back.setOnClickListener(this);
        tv_titlet = serchViewById(R.id.title_name);
        tv_titlet.setText("修改密码");

        tv_forgetPassword = serchViewById(R.id.tv_forgetPassword);
        tv_forgetPassword.setOnClickListener(this);

        btn_commit = serchViewById(R.id.btn_commit);
        btn_commit.setEnabled(false);
        btn_commit.setOnClickListener(this);

        oldPassword = serchViewById(R.id.ed_oldPassword);
        oldPassword.addTextChangedListener(textWatcher);
        newPassword = serchViewById(R.id.ed_newPassword);
        newPassword.addTextChangedListener(textWatcher);
        aginNewPassword = serchViewById(R.id.ed_aginPassword);
        aginNewPassword.addTextChangedListener(textWatcher);


    }

    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if(TextUtils.isEmpty(oldPassword.getText())||TextUtils.isEmpty(newPassword.getText())||TextUtils.isEmpty(aginNewPassword.getText())){
                btn_commit.setEnabled(false);
                btn_commit.setBackgroundResource(R.drawable.registered_btn_comit);

            }else {
                btn_commit.setEnabled(true);
                btn_commit.setBackgroundResource(R.drawable.bg_btn_selector);
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lay_back:
                ModifyPasswordActivity.this.finish();
                overridePendingTransition(R.anim.r2l_in, R.anim.r2l_out);
                break;
            case R.id.tv_forgetPassword:
                startActivity(new Intent(ModifyPasswordActivity.this, RetrievePasswordActivity.class));

                break;
            case R.id.btn_commit:
                String oldpassword = oldPassword.getText().toString();
                String newpassword = newPassword.getText().toString();
                String aginnewpassword = aginNewPassword.getText().toString();
                if (TextUtils.isEmpty(oldpassword)) {
                    showErrorDialog("您还未输入原密码");
                    return;
                }
                if (TextUtils.isEmpty(newpassword)) {
                    showErrorDialog("您还未输入新密码");
                    return;
                }
                if (TextUtils.isEmpty(aginnewpassword)) {
                    showErrorDialog( "请再次输入新密码");
                    return;
                }
                if (aginnewpassword.length()<6) {
                    showErrorDialog( "新密码不能小于6位");
                    return;
                }
                if (!newpassword.equals(aginnewpassword)) {
                    showErrorDialog("两次新密码输入不一致");
                    return;
                }
                if (NetworkUtils.isNetworkAvailable(activity)) {
                    sendCommit(oldpassword, aginnewpassword);
                } else {
                    showErrorDialog("网络异常");
                }
                break;

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void sendCommit(String oldpassword, String aginnewpassord) {
        String deviceId = SystemUtils.getDeviceKey(activity);
        String userId = userInfo.userID;

        HashMap<String, String> params = new HashMap<>();
        params.put("deviceId", deviceId);
        params.put("uid", userId);
        params.put("newPassword", aginnewpassord);
        params.put("oldPassword", oldpassword);
        showLoadingDialog();
        TaskExecutor.getInstance().execute(new PostRequestTask(params, activity, UrlConsts.USER_MODIFYPASSWORD) {
            @Override
            protected void handleResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    int code = object.getInt("code");
                    String msg = object.getString("message");
                    if(code==0000){
                        closeLoadingDialog();
                        ToastUtils.showToast(activity, "您已成功修改密码,请重新登陆");
                        application.setUserInfo(null);
                        SharedPreferencesUtils.saveValue(activity, SharedPreferencesUtils.keep_login_state, false);
                        startActivity(new Intent(ModifyPasswordActivity.this,RegisterActivity.class));
                        finish();
                        overridePendingTransition(R.anim.r2l_in, R.anim.r2l_out);
                    }else{
                        throw new Exception(msg);
                    }
                } catch (Exception e) {
                    ToastUtils.showToast(activity, e.getMessage());
//                    tv_check_error.setVisibility(View.VISIBLE);
                } finally {
                   closeLoadingDialog();
                }
            }
        });


    }

}


